import dayjs from 'dayjs';
import axios from 'axios';

interface ExpiresMap {
    [key: string]: Date;
}

const Expires: ExpiresMap = {};
const ExpiresHours: ExpiresMap = {};
const ExpiresDays: ExpiresMap = {};

interface Utils {
    getUniCode: (name: string) => string;
    sendable: (id: string, type?: 'hour' | 'day' | false) => boolean;
    setExpires: (id: string, type?: 'hour' | 'day' | false) => void;
    sendMessage: (chatid: string, text: string) => Promise<void>;
    getMyself: () => Promise<Object>;
    getContact: (wxid: string) => Promise<Object>;
}

const utils: Utils = {
    getUniCode: (name: string): string => {
        return name.replace('-USDT-SWAP', '').replace('USDT', '');
    },

    sendable: (id: string, type: 'hour' | 'day' | false = false): boolean => {
        if (!type && Expires[id] && (Expires[id] > dayjs().add(-1, 'minutes').toDate())) {
            return false;
        }

        if (type === 'hour' && ExpiresHours[id] && ExpiresHours[id] > dayjs().add(-2, 'hours').toDate()) {
            return false;
        }

        if (type === 'day' && ExpiresDays[id] && ExpiresDays[id] > dayjs().add(-12, 'hours').toDate()) {
            return false;
        }

        return true;
    },

    setExpires: (id: string, type: 'hour' | 'day' | false = false): void => {
        if (!type) {
            Expires[id] = new Date();
        }

        if (type === 'hour') {
            ExpiresHours[id] = new Date();
        }

        if (type === 'day') {
            ExpiresDays[id] = new Date();
        }
    },

    sendMessage: async (chatid: string, text: string): Promise<void> => {
        if(!(typeof(text) == 'string')){
            return console.log('send wrong content', text)
        }
        console.log({
            wxid: chatid,
            content: text,
        })
        await fetch("http://127.0.0.1:5555/api/send_txt", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                wxid: chatid,
                content: text,
            }),
        });
    },
    
    // {
    //     head_img: "https://wx.qlogo.cn/mmhead/ver_1/oib4K0kXAlzAp9HL4UsQfkdeqsh3RuXS0NficibMkMGWUKrHicZFibwVDEW48zw5IQCYhwyAby1gVAQq6Y7gibWGbaSSZlmMvSibxFkrKia3icMtHjA7Woia57pFhm8OLO9PTQicsjf/132",
    //     nick: "老田",
    //     wxcode: "wxid_1klafyrxebnb22",
    //     wxid: "wxid_1klafyrxebnb22",
    //   }
    getContact: async (wxid) =>{
        const { data } = await axios.post("http://127.0.0.1:5555/api/get_contact", {wxid});
        let user = null;
        for(let d of data.data){
            if(d.wxid == wxid) {
                user = d
            }
        }
        return user;
    },
    getMyself: async (): Promise<{ data: any }> => {
        const { data } = await axios.post("http://127.0.0.1:5555/api/get_myself");
        return JSON.parse(data.data);
    }
};

export default utils;